package com.ftg.learn.xmlinterface;

import com.ftg.learn.xmlinterface.mapper.TeacherMapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 布衣
 */
public class JavaBase {

    //xml

    //注解

    //javaBase

    public static void main(String[] args) {
        //配置核心类
        Configuration config = new Configuration();

        //环境
        TransactionFactory factory = new JdbcTransactionFactory();
        PooledDataSource dataSource = new PooledDataSource("com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/qd_db_demo", "root", "123456");
        dataSource.setLoginTimeout(1000);
        dataSource.setPoolMaximumActiveConnections(10);
        Environment env = new Environment("localMysql", factory, dataSource);
        config.setEnvironment(env);

        //向config 添加映射器
//        config.addMapper(TeacherMapper1.class);
        config.addMappers("com.ftg.learn.xmlinterface.mapper");

        //配置文件类teacher.xml添加到configuration
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("com/ftg/learn/xmlinterface/mapper/xml/teacher.xml");
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, config, "teacher.xml", config.getSqlFragments());
            mapperParser.parse();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //打印sql
        config.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);

        SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = ssfb.build(config);

        SqlSession sqlSession = build.openSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        System.out.println(mapper.showTeacherByName("张"));

        sqlSession.commit();
        sqlSession.close();

    }

}
